<?php declare(strict_types=1);

namespace app\admin\service;

use app\home\model\Message;
use think\facade\Log;

class MessageService
{
    /**
     * 列表
     * @return void
     */
    public function getMessageList($pageSize, $startDate, $endDate, $status)
    {
        $model = new Message();
        return $model
            ->where(function ($query) use ($startDate, $endDate, $status){
                if($startDate){
                    $query->where('create_time', '>=', strtotime($startDate. ' 00:00:00'));
                }
                if($endDate){
                    $query->where('create_time', '<=', strtotime($endDate.' 23:59:59'));
                }
                if ($status) {
                    $query->where('status', $status);
                }
            })
            ->order(['status'=>'asc','create_time'=>'desc'])
            ->paginate($pageSize)->each(function ($item){
                if ($item->update_time) {
                    return $item->update_time = date('Y-m-d H:i:s', $item->update_time);
                }
            });
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function edit($data)
    {
        try {
            $model = new Message();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $data['status'] = 1;
                $data['update_time'] = time();
                $item->save($data);
            }
            return true;
        } catch (\Exception $e) {
            Log::error("edit message error:". $e->getMessage());
            return false;
        }
    }

    /**
     * 获取总数
     * @param int $status
     * @return void
     */
    public function getMsgCount(int $status = -1)
    {
        $model = new Message();
        return $model->where('status', $status)->count();
    }
}